package com.ecjtu.stadiumre_servations.service.impl;

import com.alipay.api.domain.Activity;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ecjtu.stadiumre_servations.config.RabbitMQConfig;
import com.ecjtu.stadiumre_servations.config.TimeConflictChecker;
import com.ecjtu.stadiumre_servations.entity.domain.*;
import com.ecjtu.stadiumre_servations.entity.dto.GroupActivityDTO;
import com.ecjtu.stadiumre_servations.entity.dto.GroupRecordDTO;
import com.ecjtu.stadiumre_servations.mapper.BookingMapper;
import com.ecjtu.stadiumre_servations.mapper.GroupActivityMapper;
import com.ecjtu.stadiumre_servations.mapper.GroupMemberMapper;
import com.ecjtu.stadiumre_servations.mapper.GroupRecordMapper;
import com.ecjtu.stadiumre_servations.response.Result;
import com.ecjtu.stadiumre_servations.service.AlipayService;
import com.ecjtu.stadiumre_servations.service.BookingService;
import com.ecjtu.stadiumre_servations.service.GroupRecordService;
import net.bytebuddy.asm.Advice;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

import static com.ecjtu.stadiumre_servations.response.ResultCodeEnum.SELECT_SUCCESS;

@Service
public class GroupRecordServiceImpl extends ServiceImpl<GroupRecordMapper, GroupRecord> implements GroupRecordService {

    @Autowired
    private GroupRecordMapper groupRecordMapper;
    @Autowired
    private GroupMemberMapper groupMemberMapper;
    @Autowired
    private TimeConflictChecker timeConflictChecker;
    @Autowired
    private BookingService bookingService;
    @Autowired
    private AlipayService alipayService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private GroupActivityMapper groupActivityMapper;
    @Autowired
    private BookingMapper bookingMapper;


    @Override
    public Result createGroup(String userid, String activityId, LocalDateTime bookingStartTime, LocalDateTime bookingEndTime) {
        System.out.println(2222);
        // 检查时间冲突
        boolean conflictResult = timeConflictChecker.checkTimeConflictById(userid);
        if (!conflictResult) {
            return Result.fail("时间存在冲突");
        }
        // 保存拼团记录
        GroupRecord groupRecord = new GroupRecord();
        groupRecord.setActivityId(activityId);
        groupRecord.setLeaderUserId(userid);
        groupRecord.setCurrentSize(1); // 初始人数为 1
        LambdaQueryWrapper<GroupActivity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GroupActivity::getActivityId, activityId);
        GroupActivity groupActivity = groupActivityMapper.selectOne(lambdaQueryWrapper);
        groupRecord.setTargetSize(groupActivity.getGroupSize());
        groupRecord.setStartTime(bookingStartTime);
        groupRecord.setEndTime(bookingEndTime);
        groupRecord.setRecordStatus("拼团中"); // 初始状态为拼团中
        groupRecord.setRecordCreateTime(LocalDateTime.now());
        groupRecord.setUpdateTime(LocalDateTime.now());
        int result = groupRecordMapper.insert(groupRecord);
        if (result > 0) {
            // 创建拼团成功后，添加团长作为第一个成员
            GroupMember leader = new GroupMember();
            leader.setGroupRecordId(groupRecord.getRecordId());
            leader.setUserId(groupRecord.getLeaderUserId());
            leader.setIsLeader("true"); // 团长
            leader.setPayStatus("已支付"); // 已支付
            leader.setJoinTime(LocalDateTime.now());

            if (groupMemberMapper.insert(leader) > 0) {
                return Result.ok("拼团创建成功");
            }
        }

        return Result.fail("拼团创建失败");
    }

    //    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public Result joinGroup(String userId, String groupRecordId) {
//        // 参数校验
//        if (userId == null || groupRecordId == null) {
//            return Result.fail("用户ID和拼团ID不能为空");
//        }
//
//        // 查询拼团记录
//        GroupRecord groupRecord = groupRecordMapper.selectById(groupRecordId);
//        if (groupRecord == null) {
//            return Result.fail("拼团记录不存在");
//        }
//
//        // 检查拼团状态
//        if (!"拼团中".equals(groupRecord.getRecordStatus())) { // 非拼团中状态
//            return Result.fail("该拼团已结束或已关闭");
//        }
//
//        // 检查拼团是否已满员
//        if (groupRecord.getCurrentSize() >= groupRecord.getTargetSize()) {
//            return Result.fail("该拼团已满员");
//        }
//
//        // 检查用户是否已在拼团中
//        LambdaQueryWrapper<GroupMember> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(GroupMember::getUserId, userId)
//                .eq(GroupMember::getGroupRecordId, groupRecordId);
//        if (groupMemberMapper.selectCount(queryWrapper) > 0) {
//            return Result.fail("您已在该拼团中");
//        }
//
//        // 检查时间冲突
//        boolean conflictResult = timeConflictChecker.checkTimeConflictById(userId);
//        if (!conflictResult) {
//            return Result.fail("时间存在冲突");
//        }
//
//        // 创建拼团成员记录
//        GroupMember member = new GroupMember();
//        member.setGroupRecordId(groupRecordId);
//        member.setUserId(userId);
//        member.setIsLeader("false"); // 非团长
//        member.setPayStatus("待支付"); // 待支付
//        member.setJoinTime(LocalDateTime.now());
//
//        int insertResult = groupMemberMapper.insert(member);
//        if (insertResult <= 0) {
//            return Result.fail("加入拼团失败");
//        }
//
//        // 更新拼团人数
//        groupRecord.setCurrentSize(groupRecord.getCurrentSize() + 1);
//
//            // 拼团成功，调用支付宝支付
//            try {
//                // 获取拼团对应的预约信息
//                booking = bookingService.getById(groupRecordId);
//                if (booking == null) {
//                    return Result.fail("预约信息不存在");
//                }
//
//                // 生成订单号
//                String payId = groupRecordId;
//
//                // 计算预约总价
//                double price = booking.getBookingTotalPrice();
//                String orderName = "场馆拼团预约支付";
//                String body = "场馆拼团预约支付，预约编号：" + booking.getBookingId();
//                Map<String, String> sourceMap = new HashMap<>();
//                sourceMap.put("out_trade_no", payId);  // 订单号
//                sourceMap.put("total_amount", String.valueOf(price));  // 总计
//                sourceMap.put("body", body); // 描述
//                sourceMap.put("order_name", orderName); // 订单名
//                String form = alipayService.toAlipay(sourceMap);
//                // 返回支付表单给前端
//                return Result.ok().data("form", form);
//            } catch (Exception e) {
//                e.printStackTrace();
//                return Result.fail("调用支付宝支付失败");
//            }
//        }
//        int updateResult = groupRecordMapper.updateById(groupRecord);
//        if (updateResult <= 0) {
//            // 回滚插入的成员记录
//            throw new RuntimeException("更新拼团人数失败");
//        }
//        return Result.ok("加入拼团成功");
//    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result joinGroup(String userId, String activityId) {
        // 参数校验
        if (userId == null || activityId == null) {
            return Result.fail("用户ID和活动ID不能为空");
        }
        // 查询拼团记录
        LambdaQueryWrapper<GroupRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GroupRecord::getActivityId, activityId);
        GroupRecord groupRecord = groupRecordMapper.selectOne(lambdaQueryWrapper);
        if (groupRecord == null) {
            return Result.fail("拼团记录不存在");
        }
        // 检查拼团状态
        if (!"拼团中".equals(groupRecord.getRecordStatus())) { // 非拼团中状态
            return Result.fail("该拼团已结束或已关闭");
        }

        // 检查拼团是否已满员
        if (groupRecord.getCurrentSize() >= groupRecord.getTargetSize()) {
            return Result.fail("该拼团已满员");
        }

        // 检查用户是否已在拼团中
        LambdaQueryWrapper<GroupMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GroupMember::getUserId, userId)
                .eq(GroupMember::getGroupRecordId, groupRecord.getRecordId());
        if (groupMemberMapper.selectCount(queryWrapper) > 0) {
            return Result.fail("您已在该拼团中");
        }

        // 检查时间冲突
        boolean conflictResult = timeConflictChecker.checkTimeConflictById(userId);
        if (conflictResult) {
            return Result.fail("时间存在冲突");
        }

        //创建第一条预约记录
        // 创建拼团成员记录
        GroupMember member1 = new GroupMember();
        member1.setMemberId(UUID.randomUUID().toString());
        member1.setGroupRecordId(groupRecord.getRecordId());
        member1.setUserId(userId);
        member1.setIsLeader("false"); // 非团长
        member1.setPayStatus("待支付"); // 待支付
        member1.setJoinTime(LocalDateTime.now());
        int insertResult = groupMemberMapper.insert(member1);
        if (insertResult <= 0) {
            return Result.fail("加入拼团失败");
        }
        // 准备支付宝支付参数
        GroupActivity groupActivity = groupActivityMapper.selectById(activityId);
        Map<String, String> alipayParams = new HashMap<>();
        alipayParams.put("out_trade_no", member1.getMemberId()); // 使用成员ID作为外部交易号
        alipayParams.put("total_amount", String.format("%.2f", groupActivity.getActivityPrice())); // 支付金额
        alipayParams.put("order_name", "加入拼团支付"); // 订单名称
        alipayParams.put("body", "加入拼团活动：" + groupActivity.getActivityName()); // 订单描述
        // 更新拼团人数
        groupRecord.setCurrentSize(groupRecord.getCurrentSize() + 1);
        int updateResult = groupRecordMapper.updateById(groupRecord); // 添加更新操作
        if (updateResult <= 0) {
            return Result.fail("拼团人数更新失败");
        }
        Booking booking = new Booking();
                booking.setBookingId(UUID.randomUUID().toString());
                booking.setStudentId(userId);
                booking.setVenueId(groupActivity.getActivityVenueId());
                booking.setBookingStartTime(groupRecord.getStartTime());
                booking.setBookingEndTime(groupRecord.getEndTime());
                booking.setBookingTotalPrice(groupActivity.getActivityPrice());
                booking.setCreateTime(LocalDateTime.now());
                booking.setBookingType("拼团预约");
                booking.setBookingStatus("已支付");
                bookingService.save(booking);
        // 添加通知逻辑：短信/站内信通知团员
        // 如果达到目标人数，更新拼团状态为已成团 并为每个成员创建预约记录
        if (groupRecord.getCurrentSize().equals(groupRecord.getTargetSize())) {
            groupRecord.setRecordStatus("已成团"); // 已成团
            groupRecordMapper.updateById(groupRecord);
            groupActivity.setActivityStatus("已成团");
            groupActivityMapper.updateById(groupActivity);
        }
//        // 查询所有拼团成员
//        LambdaQueryWrapper<GroupMember> memberQueryWrapper = new LambdaQueryWrapper<>();
//        memberQueryWrapper.eq(GroupMember::getGroupRecordId, groupRecord.getRecordId());
//        List<GroupMember> groupMembers = groupMemberMapper.selectList(memberQueryWrapper);
//        for (GroupMember member : groupMembers) {
//            if (member.getIsLeader().equals("false")){
//                // 为每个成员创建预约记录
//                Booking booking = new Booking();
//                booking.setBookingId(UUID.randomUUID().toString());
//                booking.setStudentId(member.getUserId());
//                booking.setVenueId(groupActivity.getActivityVenueId());
//                booking.setBookingStartTime(groupRecord.getStartTime());
//                booking.setBookingEndTime(groupRecord.getEndTime());
//                booking.setBookingTotalPrice(groupActivity.getActivityPrice());
//                booking.setCreateTime(LocalDateTime.now());
//                booking.setBookingType("拼团预约");
//                booking.setBookingStatus("已支付");
//                bookingService.save(booking);
//            }
//        }
        try {
            // 调用支付宝支付接口生成支付表单
            String form = alipayService.toAlipay(alipayParams);
            // 发送支付请求到消息队列，等待支付结果通知
            rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME, RabbitMQConfig.PAYMENT_REQUEST_ROUTING_KEY, alipayParams);
            // 返回支付表单给前端，让用户进行支付
            System.out.println("支付宝");
            System.out.println(form);
            return Result.ok().data("form", form);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("调用支付宝支付失败");
        }
    }

//
//            // 准备支付宝支付参数
//            Map<String, String> alipayParams = new HashMap<>();
//            alipayParams.put("out_trade_no", booking.getBookingId()); // 使用预约ID作为外部交易号
//            alipayParams.put("total_amount", String.format("%.2f", booking.getBookingTotalPrice())); // 支付金额
//            alipayParams.put("order_name", groupActivity.getActivityName() + "拼团预约支付"); // 订单名称
//            alipayParams.put("body", "拼团预约：" +
//                    "开始时间=" + booking.getBookingStartTime() +
//                    ",结束时间=" + booking.getBookingEndTime()); // 订单描述
//            // 发送支付通知消息到RabbitMQ
//            Map<String, String> paymentNoticeMessage = new HashMap<>();
//            paymentNoticeMessage.put("userId", member.getUserId());
//            paymentNoticeMessage.put("message", "您的拼团已成团，请在规定时间内完成支付。");
//
//            rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,
//                    "payment.notice.routing.key", paymentNoticeMessage);
//            // 发送支付请求消息到RabbitMQ（异步处理支付请求）
//            rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,
//                    RabbitMQConfig.PAYMENT_REQUEST_ROUTING_KEY, alipayParams);
//
//            // 发送延迟消息到延迟队列（用于30分钟未支付自动取消）
//            Map<String, String> timeoutMessage = new HashMap<>();
//            timeoutMessage.put("bookingId", booking.getBookingId());
//            rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,
//                    RabbitMQConfig.PAYMENT_TIMEOUT_DELAYED_ROUTING_KEY, timeoutMessage);
//        }
//
//        return Result.ok("拼团已成团，请等待支付处理");
//    }
//
//    return Result.ok("加入拼团成功");
//    // 更新拼团人数
//    groupRecord.setCurrentSize(groupRecord.getCurrentSize() + 1);
//    int updateResult = groupRecordMapper.updateById(groupRecord); // 添加更新操作
//    if (updateResult <= 0) {
//        return Result.fail("拼团人数更新失败");
//    }
//
//        // 添加通知逻辑：短信/站内信通知团员
//    // 如果达到目标人数，更新拼团状态为已成团 并在预约表中将团长作为预约人生成对应的预约记录
//    if (groupRecord.getCurrentSize().equals(groupRecord.getTargetSize())) {
//        groupRecord.setRecordStatus("已成团"); // 已成团
//        Booking booking = new Booking();
//        booking.setBookingId(groupRecord.getRecordId());
//        booking.setStudentId(groupRecord.getLeaderUserId());
//        GroupActivity groupActivity = groupActivityMapper.selectById(groupRecord.getActivityId());
//        booking.setVenueId(groupActivity.getActivityVenueId());
//        booking.setBookingStartTime(groupRecord.getStartTime());
//        booking.setBookingEndTime(groupRecord.getEndTime());
//        booking.setBookingTotalPrice(groupActivity.getActivityPrice()*groupRecord.getTargetSize());
//        booking.setCreateTime(LocalDateTime.now());
//        booking.setBookingType("拼团预约");
////        // 拼团成功，调用支付宝支付
////        try {
////            // 获取拼团对应的预约信息
////            booking = bookingService.getById(groupRecord.getRecordId());
////            if (booking == null) {
////                return Result.fail("预约信息不存在");
////            }
////
////            // 生成订单号
////            String payId = groupRecord.getRecordId();
////
////            // 计算预约总价
////            double price = booking.getBookingTotalPrice();
////            String orderName = "场馆拼团预约支付";
////            String body = "场馆拼团预约支付，预约编号：" + booking.getBookingId();
////            Map<String, String> sourceMap = new HashMap<>();
////            sourceMap.put("out_trade_no", payId);  // 订单号
////            sourceMap.put("total_amount", String.valueOf(price));  // 总计
////            sourceMap.put("body", body); // 描述
////            sourceMap.put("order_name", orderName); // 订单名
////            String form = alipayService.toAlipay(sourceMap);
////            // 返回支付表单给前端
////            return Result.ok().data("form", form);
////        } catch (Exception e) {
////            e.printStackTrace();
////            return Result.fail("调用支付宝支付失败");
////        }
////    }
////    int updateResult = groupRecordMapper.updateById(groupRecord);
////    if (updateResult <= 0) {
////        // 回滚插入的成员记录
////        throw new RuntimeException("更新拼团人数失败");
//        groupRecordMapper.updateById(groupRecord);
//    }
//    return Result.ok("加入拼团成功");
    @Override
    public Result getGroupByVenueId(Page<GroupRecord> page, String venueId) {
        LambdaQueryWrapper<GroupRecord>lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GroupRecord::getActivityId,venueId);
        List<GroupRecord> list = groupRecordMapper.selectList(lambdaQueryWrapper);
        if (list==null){
            return Result.ok("该场馆不存在任何拼团活动");
        }
        return Result.build(list,SELECT_SUCCESS);
    }

    @Override
    public Result listGroup(Page<GroupRecord> page) {
        return Result.build(groupRecordMapper.selectPage(page,null),SELECT_SUCCESS);
    }
}